﻿using System;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Presenter.DocumentIdConfig;
using MS.InformationManagement.Presenter.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.Support;
using AjaxControlToolkit;
using System.Text;
using System.Web.UI.WebControls;
using System.Linq;
using MS.InformationManagement.Support.Constants;


namespace MS.InformationManagement.DocumentIDProviders.StandardConfigurator
{
    public partial class StandardConfiguratorUserControl : BaseControl, IDocumentIdConfigView
    {
        #region [Private Fields]

        DocumentIdConfigPresenter _Presenter;

        #endregion

        #region [Event Handlers]

        protected void grdDocTypes_RowCreated(Object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
            //{
            //    TipoDeRadicado data = e.Row.DataItem as TipoDeRadicado;
            //    if (data != null)
            //    {
            //        ImageButton deleteButton = e.Row.FindControl("imb_delete") as ImageButton;
            //        deleteButton.OnClientClick = string.Format("return confirm('Esta seguro de que desea eliminar el tipo de radicado {0}');", data.Title);
            //    }
            //}
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    _Presenter.HandleLoad();
                }
                catch (Exception ex)
                {
                    HandleError(ex);
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            RegisterControlInitialization();
            _Presenter = new DocumentIdConfigPresenter(this);
            txtbDocTypeName.Required("Este campo es requerido", btnSave.ValidationGroup, ValidatorCalloutPosition.BottomRight);
            txtbDocTypeName.RegularExpression(RegularExpresions.EXP_ALFANUMERIC_NO_TILDE_NO_NUMBERS, ExceptionConstants.ERROR_INVALID_CHARACTERS, btnSave.ValidationGroup, ValidatorCalloutPosition.BottomRight);
            txtbRadTypeCode.Required("Este campo es requierido", btnSave.ValidationGroup, ValidatorCalloutPosition.BottomRight);
            txtbRadTypeCode.RegularExpression(RegularExpresions.EXP_ALFANUMERIC_NO_TILDE_NO_NUMBERS, ExceptionConstants.ERROR_INVALID_CHARACTERS, btnSave.ValidationGroup, ValidatorCalloutPosition.BottomRight);
            DocumentTypeId = string.IsNullOrEmpty(Request.QueryString.Get("radTypeId")) ? 0 : Convert.ToInt32(Request.QueryString.Get("radTypeId"));
        }

        protected void imb_delete_DataBinding(object sender, EventArgs e)
        {
            ImageButton btn = sender as ImageButton;
            btn.OnClientClick = string.Format("return confirm('Esta seguro que desea eliminar el tipo de radicado {0}');", btn.CommandName);
        }

        protected void imb_restart_DataBinding(object sender, EventArgs e)
        {
            ImageButton btn = sender as ImageButton;
            btn.OnClientClick = string.Format("return confirm('Esta seguro que desea reiniciar el contador del tipo de radicado {0}');", btn.CommandName);
        }

        protected void imb_edit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            ImageButton btn = sender as ImageButton;
            if (string.IsNullOrEmpty(Request.Url.Query))
            {
                Response.Redirect(string.Format("~/sites/docs{0}?radTypeId={1}", Request.Url.PathAndQuery, btn.CommandArgument));
            }
            else
            {
                Response.Redirect(string.Format("~/sites/docs{0}?radTypeId={1}", Request.Url.PathAndQuery.Replace(Request.Url.Query, string.Empty), btn.CommandArgument));
            }
        }

        protected void imb_delete_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ImageButton trigger = sender as ImageButton;
                _Presenter.DeleteDocType(trigger.CommandArgument);
                _Presenter.HandleLoad();
                HandleSuccess("El tipo de radicado ha sido eliminado exitosamente", null);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void imb_restart_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                ImageButton trigger = sender as ImageButton;
                _Presenter.RestartDocType(trigger.CommandArgument);
                
                HandleSuccess("El contador del tipo de radicado ha sido reiniciado exitosamente", null);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region [IDocumentIdConfigView Members]

        public int DocumentTypeId
        {
            get { return string.IsNullOrEmpty(hdfDocTypeId.Value) ? 0 : Convert.ToInt32(hdfDocTypeId.Value); }
            set { hdfDocTypeId.Value = value.ToString(); }
        }

        public string DocumentTypeName
        {
            get { return txtbDocTypeName.Text; }
            set { txtbDocTypeName.Text = value; }
        }

        public string DocumentTypeCode
        {
            get { return txtbRadTypeCode.Text; }
            set { txtbRadTypeCode.Text = value; }
        }

        public string Strategy
        {
            get { return hdfStategy.Value; }
            set
            {
                hdfStategy.Value = value;
                switch (value)
                {
                    case "Create":
                        ltrTitle.Text = "Crear un nuevo tipo de radicado";
                        btnSave.Text = "Guardar";
                        break;
                    case "Update":
                        ltrTitle.Text = "Actualizar un tipo de radicado existente";
                        btnSave.Text = "Actualizar";
                        break;
                }
            }
        }

        public System.Collections.Generic.IEnumerable<CampoDisponibleDeConfiguracionDeRadicado> AvailableFields
        {
            get
            {
                return Cache[string.Format("AvailableFields-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] as System.Collections.Generic.IEnumerable<CampoDisponibleDeConfiguracionDeRadicado>;
            }
            set
            {
                Cache[string.Format("AvailableFields-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] = value;
                //lstbFields.DataSource = value;
                //lstbFields.DataBind();
                rptAvailableFields.DataSource = value;
                rptAvailableFields.DataBind();
            }
        }

        public System.Collections.Generic.IEnumerable<ElementoDeConfiguracionDeEstructuraDeRadicado> ConfiguredFields
        {
            get
            {
                return Cache[string.Format("ConfiguredFields-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] as System.Collections.Generic.IEnumerable<ElementoDeConfiguracionDeEstructuraDeRadicado>;
            }
            set
            {
                Cache[string.Format("ConfiguredFields-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] = value;
                rptConfiguredItems.DataSource = value;
                rptConfiguredItems.DataBind();
            }
        }

        public System.Collections.Generic.IEnumerable<TipoDeRadicado> DocumentTypes
        {
            get
            {
                return Cache[string.Format("DocumentTypes-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] as System.Collections.Generic.IEnumerable<TipoDeRadicado>;
            }
            set
            {
                Cache[string.Format("DocumentTypes-{0}", SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain())] = value;
                grdDocTypes.DataSource = value;
                grdDocTypes.DataBind();
            }
        }

        #endregion

        #region [Private Members]

        private void RegisterControlInitialization()
        {
            StringBuilder javascript = new StringBuilder("<script type='text/javascript'>$(document).ready(function(){");
            javascript
                .Append("MS.InformationManagement.StandardDocumentIDConfigurator.Initialize('")
                .Append(hdfDocTypeId.ClientID)
                .Append("', '")
                .Append(txtbDocTypeName.ClientID)
                .Append("', '")
                .Append(txtbRadTypeCode.ClientID)
                .Append("', '")
                .Append("config-area")
                .Append("', '")
                .Append("available-fields")
                .Append("', '")
                .Append(btnSave.ClientID)
                .Append("', '")
                .Append(hdfStategy.ClientID)
                .Append("');});</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "initialization", javascript.ToString());
        }

        #endregion


    }
}
